// CSE 142, Winter 2008, Marty Stepp // // This program demonstrates a "sentinel" value, // a special value that signals the end of user input. // Sentinel loops are an example of a fencepost problem. // // This version is modified to use a break statement. // This would be considered bad style and shouldn't be used on your homework. // // We're showing it because it's something you'll see in other people's code, // so it's useful to be aware of it and understand why it is bad to use it. import java.util.*; public class Sentinel3 { public static void main(String[] args) { Scanner console = new Scanner(System.in); int sum = 0; while (true) { // read first number (place first "post") System.out.print("Enter a number (-1 to quit): "); int number = console.nextInt(); if (number < 0) { // stop this loop immediately (bad style, don't use on HW5) break; } // add number to sum (place a "wire") sum = sum + number; } System.out.println("The total was " + sum); } }